package com.letoken.platform.repo.app.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.repo.app.dao.BlockchainMapper;
import com.letoken.platform.repo.app.po.Blockchain;
import com.letoken.platform.repo.app.redis.AppBlockchainRedis;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author letokenlabs
 * @date 2022/11/18$
 */
@Log4j2
@Repository
public class BlockchainManager {

    @Autowired
    private BlockchainMapper blockchainMapper;

    public Integer getChainId(String netType) {
        Blockchain blockchain = AppBlockchainRedis.me().getClassObject(netType);
        if (blockchain != null) {
            return blockchain.getId();
        }
        if (blockchain == null) {
            blockchain = queryByNetwork(netType);
            if (blockchain != null) {
                AppBlockchainRedis.me().put(netType, blockchain);
                return blockchain.getId();
            }
        }
        return 0;
    }

    public String getNetType(Integer chainId) {
        Blockchain blockchain = AppBlockchainRedis.me().getClassObject(chainId.toString());
        if (blockchain == null) {
            blockchain = blockchainMapper.selectById(chainId);
            if (blockchain != null) {
                AppBlockchainRedis.me().put(chainId.toString(), blockchain);
                return blockchain.getNetType();
            }
        }
        return blockchain.getNetType();
    }


    public Blockchain queryByNetwork(String netType) {
        QueryWrapper<Blockchain> query = new QueryWrapper<>();
        query.eq("net_type", netType);
        return blockchainMapper.selectOne(query);
    }

}
